package com.chookss.view;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chookss.R;
import com.chookss.home.entity.StudyPlanDayEntity;
import com.chookss.tools.MyToast;
import com.chookss.tools.Utils;
import com.chookss.view.listener.StudyDialogListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import io.reactivex.annotations.NonNull;
import io.reactivex.annotations.Nullable;


public class StudyPlanDialog extends Dialog {
    private List<String> months = new ArrayList<>();
    private List<List<StudyPlanDayEntity>> dayLists = new ArrayList<>();
    private Context context;
    private StudyDialogListener listener = null;
    private LinearLayout arrow_left, arrow_right;
    private TextView tvMonth, tvType, tvCancel, tvSure;
    private NoScrollViewPager vp;
    private PagerAdapter mPagerAdapter;
    private int position = 0;
    private String currentDate, choiceDate, cycle;

    public StudyPlanDialog(@NonNull Context context, List<List<StudyPlanDayEntity>> dayLists, List<String> months, String cycle, StudyDialogListener listener) {
        super(context);
        this.context = context;
        this.dayLists = dayLists;
        this.months = months;
        this.cycle = cycle;
        this.listener = listener;
        initLayoutRes();
    }

    public StudyPlanDialog(@NonNull Context context, int themeResId) {
        super(context, themeResId);
        initLayoutRes();
    }

//    public void setSelect(String date) {
//        adapter.setSelect(position);
//    }

    private void initLayoutRes() {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        SimpleDateFormat simpleDateFormat;
        if ("3".equals(cycle)) {
            simpleDateFormat = new SimpleDateFormat("yyyy-MM");
        } else {
            simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        }
        Date date = new Date(System.currentTimeMillis());
        currentDate = simpleDateFormat.format(date);
        View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_study_plan, null);
        arrow_left = view.findViewById(R.id.arrow_left);
        arrow_right = view.findViewById(R.id.arrow_right);
        tvMonth = view.findViewById(R.id.tvMonth);
        tvType = view.findViewById(R.id.tvType);
        tvCancel = view.findViewById(R.id.tvCancel);
        tvSure = view.findViewById(R.id.tvSure);
        vp = view.findViewById(R.id.vp);
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) vp.getLayoutParams();
        if ("3".equals(cycle)) {
            tvMonth.setText(months.get(0));
            tvType.setText("年");
            params.height = Utils.dip2px(context, 90);
            tvSure.setText("回到当月");
        } else {
            tvMonth.setText(Utils.getAccurateDate2(months.get(0), 5, 7));
            tvType.setText("月");
            params.height = Utils.dip2px(context, 222);
            tvSure.setText("回到今天");
        }
        vp.setLayoutParams(params);
        mPagerAdapter = new PagerAdapters();
        vp.setAdapter(mPagerAdapter);
        vp.addOnPageChangeListener(pageChangeListener);

        tvCancel.setOnClickListener(v -> dismiss());
        tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                choiceDate = currentDate;
                if (listener != null) {
                    listener.onStudyClick(currentDate);
                }
                vp.setAdapter(mPagerAdapter);
                mPagerAdapter.notifyDataSetChanged();
                currentDay();
                dismiss();
            }
        });
        arrow_left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (position > 0) {
                    vp.setCurrentItem(position - 1);
                } else {
                    if ("3".equals(cycle)) {
                        MyToast.show("已经是计划的第一年了");
                    } else {
                        MyToast.show("已经是计划的第一个月了");
                    }

                }

            }
        });
        arrow_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (position < dayLists.size() - 1) {
                    vp.setCurrentItem(position + 1);
                } else {
                    if ("3".equals(cycle)) {
                        MyToast.show("已经是计划的最后一年了");
                    } else {
                        MyToast.show("已经是计划的最后一个月了");
                    }

                }
            }
        });
        if (months.size() == 1) {
            arrow_left.setVisibility(View.INVISIBLE);
            arrow_right.setVisibility(View.INVISIBLE);
        } else if (months.size() > 1) {
            arrow_left.setVisibility(View.INVISIBLE);
            arrow_right.setVisibility(View.VISIBLE);
        }
        currentDay();
        setContentView(view);
        initBottom();
    }

    /**
     *  回到当天
     */
    private void currentDay() {
        for (int i = 0; i < months.size(); i++) {
            if ("3".equals(cycle)) {
                if (Utils.getAccurateDate2(currentDate, 0, 4).equals(months.get(i))) {
                    vp.setCurrentItem(i);
                }
            } else {
                if (Utils.getAccurateDate2(currentDate, 0, 7).equals(months.get(i))) {
                    vp.setCurrentItem(i);
                }
            }
        }
    }

    protected void initBottom() {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        Window wm = getWindow();
        lp.width = Utils.getScreenWidthPixel(context) - Utils.dip2px(context, 24);
        lp.height = lp.WRAP_CONTENT;
        lp.dimAmount = 0.6f;
        wm.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        wm.setGravity(Gravity.CENTER);
        wm.setWindowAnimations(R.style.DialogFullWidthDimNotEnabled);
        getWindow().setAttributes(lp);
    }

    protected void safeDismiss() {
        if (isShowing()) {
            dismiss();
        }
    }

    /**
     * 页面滚动监听器
     */
    private ViewPager.OnPageChangeListener pageChangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageSelected(int index) {
            if ("3".equals(cycle)) {
                tvMonth.setText(months.get(index));
            } else {
                tvMonth.setText(Utils.getAccurateDate2(months.get(index), 5, 7));
            }
            position = index;
            if (position == 0) {
                arrow_left.setVisibility(View.INVISIBLE);
                if (months.size() > 1) {
                    arrow_right.setVisibility(View.VISIBLE);
                } else {
                    arrow_right.setVisibility(View.INVISIBLE);
                }
            } else if (months.size() - 1 == position) {
                arrow_right.setVisibility(View.INVISIBLE);
                if (months.size() > 1) {
                    arrow_left.setVisibility(View.VISIBLE);
                } else {
                    arrow_left.setVisibility(View.INVISIBLE);
                }
            } else if (position > 0 && position < months.size() - 1) {
                arrow_left.setVisibility(View.VISIBLE);
                arrow_right.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }
    };

    class PagerAdapters extends PagerAdapter {
        @Override
        // 获取当前窗体界面数
        public int getCount() {
            return dayLists.size();
        }

        @Override
        // 断是否由对象生成界面
        public boolean isViewFromObject(View arg0, Object arg1) {
            // TODO Auto-generated method stub
            return arg0 == arg1;
        }

        @SuppressLint("CheckResult")
        @Override
        public Object instantiateItem(ViewGroup container, int position) {

            View view = View.inflate(context, R.layout.item_study_plan_rv, null);
            RecyclerView itemStudyRv = view.findViewById(R.id.itemStudyRv);
            MyStudyDayAdapter adapter = new MyStudyDayAdapter(R.layout.item_study_plan_day_dialog, context, dayLists.get(position), position);
            GridLayoutManager gridLayoutManager1;
            if ("3".equals(cycle)) {
                gridLayoutManager1 = new GridLayoutManager(context, 6);
            } else {
                gridLayoutManager1 = new GridLayoutManager(context, 7);
            }
            itemStudyRv.setLayoutManager(gridLayoutManager1);
            itemStudyRv.setAdapter(adapter);
            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }

    }

    class MyStudyDayAdapter extends BaseQuickAdapter<StudyPlanDayEntity, BaseViewHolder> {
        private Context context;
        private int indexMonth;

        public MyStudyDayAdapter(int layoutResId, Context context, @Nullable List<StudyPlanDayEntity> data, int indexMonth) {
            super(layoutResId, data);
            this.context = context;
            this.indexMonth = indexMonth;
        }

        @Override
        protected void convert(BaseViewHolder helper, StudyPlanDayEntity item) {
            TextView tvTime = helper.getView(R.id.tvTime);
            tvTime.setText(item.getCreateTime());
            if ("1".equals(item.getIfComplete())) {
                //完成
                tvTime.setTextColor(Color.parseColor("#03B8F3"));
                tvTime.setBackgroundResource(R.drawable.shape_circle_2f_03b8f3);
            } else if ("0".equals(item.getIfComplete())) {
                //未完成
                tvTime.setTextColor(Color.parseColor("#333333"));
                tvTime.setBackgroundResource(R.drawable.shape_circle_eaeaea);
            }
            int timeCompare = 3;
            if ("3".equals(cycle)) {
                timeCompare = Utils.getMonthCompareSize(currentDate, months.get(indexMonth) + "-" + item.getCreateTime());
            } else {
                timeCompare = Utils.getTimeCompareSize(currentDate, months.get(indexMonth) + "-" + item.getCreateTime());
            }
            if (3 == timeCompare) {
                //还未开始
                tvTime.setTextColor(Color.parseColor("#333333"));
                tvTime.setBackgroundResource(R.drawable.shape_circle_white);
            }
            if (Utils.isNull(choiceDate)) {
                if (currentDate.equals(months.get(indexMonth) + "-" + item.getCreateTime())) {
                    //还未选择时候，默认是当前时间被选中
                    tvTime.setTextColor(Color.parseColor("#ffffff"));
                    tvTime.setBackgroundResource(R.drawable.shape_circle_03b8f3);
                }
            } else {
                if (choiceDate.equals(months.get(indexMonth) + "-" + item.getCreateTime())) {
                    //选中的
                    tvTime.setTextColor(Color.parseColor("#ffffff"));
                    tvTime.setBackgroundResource(R.drawable.shape_circle_03b8f3);
                }
            }

            tvTime.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    choiceDate = months.get(indexMonth) + "-" + item.getCreateTime();
                    vp.setAdapter(mPagerAdapter);
                    mPagerAdapter.notifyDataSetChanged();
                    vp.setCurrentItem(position);
                    if (listener != null) {
                        listener.onStudyClick(choiceDate);
                    }
                    dismiss();
                }
            });
        }
    }

    private void changeBg(TextView tv, StudyPlanDayEntity item) {

    }

}
